package com.example.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.mapper.UsersMapper;
import com.example.pojo.*;
import com.example.service.IUsersService;
import com.example.utils.AlipayConfig;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.Date;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2024-06-01
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Resource
    private IUsersService usersService;

    @Resource
    private UsersMapper usersMapper;

    public UsersController() {
    }

    @RequestMapping("getAllUsers")
    public List<Users> getAllUsers(){
        return usersService.getAllUsers();
    }

    @RequestMapping("getFindUsers")
    public List<Users> getFindUsers(@RequestParam("select") String select,@RequestParam("input") String input){
        return usersService.getFindUsers(select,input);
    }

    @RequestMapping("StatusChange")
    public void StatusChange(@RequestParam("status") int status,@RequestParam("uid") int uid){
        usersService.StatusChange(status,uid);
    }

    @GetMapping("login")
    public Users Login(@RequestParam("name") String name,@RequestParam("password") String password,@RequestParam("captcha") String captcha, HttpServletRequest request){
        // 获取会话中的验证码
        HttpSession session = request.getSession();
        String sessionCaptcha = (String) session.getAttribute("captcha");
        // 验证用户输入的验证码是否正确
        if (captcha != null && captcha.equalsIgnoreCase(sessionCaptcha)) {
            return usersService.Login(name,password);
        }
        return null;

    }

    @GetMapping("register")
    public void Register(@RequestParam("name") String name,@RequestParam("phone") String phone,@RequestParam("password") String password){
        usersService.Register(name,phone,password);
    }

    @GetMapping("more")
    public void More(@RequestParam("uid") int uid){
        usersService.More(uid);
    }

    //主页面的功能  找到对应的人信息
    @GetMapping("findByName_pwd")
    public Users findByName_pwd(@RequestParam("name")String name,@RequestParam("password")String password){
        return usersService.findByName_pwd(name,password);
    }

    @GetMapping("findByUid")
    public Users findByUid(@RequestParam("uid")Integer uid){
        return usersService.findByUid(uid);
    }

    @GetMapping("findApply")
    public List<Users> findApply(@RequestParam("bid") Integer bid){
        return usersService.findApply(bid);
    }

    @GetMapping("findInformation")
    public  List<Posts> findInformation(@RequestParam("uid") Integer uid){
        return usersService.findInformation(uid);
    }

    @GetMapping("findAttention")
    public List<Users> findAttention(@RequestParam("uid") Integer uid){
        return usersService.findAttention(uid);
    }


    // 生成验证码
    @Resource
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = defaultKaptcha.createText();
        request.getSession().setAttribute("captcha", capText);

        BufferedImage bi = defaultKaptcha.createImage(capText);
        ImageIO.write(bi, "jpg", response.getOutputStream());
    }

    //用户的关注   与 私信
    @GetMapping("/gz")
    public boolean gz(@RequestParam("uid") Integer uid, @RequestParam("otherid") Integer otherid) {
        try {
            Boolean result = usersService.gz(uid, otherid); // 调用目标服务的方法
            // 处理 null 值的情况
            if (result == null) {
                return false; // 或者抛出异常
            } else {
                return result; // 返回有效的布尔值
            }
        } catch (Exception e) {
            // 处理连接异常
            return false; // 返回适当的错误处理结果
        }
    }



    @GetMapping("/addGz")
    public boolean addGz(@RequestParam("uid") Integer uid,@RequestParam("otherid") Integer otherid){
        return usersService.addGz(uid,otherid);
    }

    @GetMapping("delGz")
    public boolean delGz(@RequestParam("uid") Integer uid,@RequestParam("otherid") Integer otherid){
        return usersService.delGz(uid,otherid);
    }

    @GetMapping("/gzbar")
    public boolean gzbar(@RequestParam("uid") Integer uid, @RequestParam("bid") Integer bid) {
        try {
            Boolean result = usersService.gzbar(uid, bid); // 调用目标服务的方法
            // 处理 null 值的情况
            if (result == null) {
                return false; // 或者抛出异常
            } else {
                return result; // 返回有效的布尔值
            }
        } catch (Exception e) {
            // 处理连接异常
            return false; // 返回适当的错误处理结果
        }
    }

    @GetMapping("/addGzbar")
    public boolean addGzbar(@RequestParam("uid") Integer uid,@RequestParam("bid") Integer bid){
        return usersService.addGzbar(uid,bid);
    }

    @GetMapping("delGzbar")
    public boolean delGzbar(@RequestParam("uid") Integer uid,@RequestParam("bid") Integer bid){
        return usersService.delGzbar(uid,bid);
    }

//    个人中心
    @GetMapping("updateUser")
    public void updateUser(@RequestParam("uid") Integer uid,@RequestParam("name") String name,@RequestParam("phone") String phone,@RequestParam("password") String password,
                           @RequestParam("image") String image,@RequestParam("gender") String gender,@RequestParam("age") Integer age, @RequestParam("ipaddress") String ipaddress){
        usersService.updateUser(uid,name,phone,password,image,gender,age,ipaddress);
    }

    @GetMapping("update_image")
    public boolean updateUser_image(@RequestParam("uid") Integer uid,@RequestParam("image") String image){
        return usersService.updateUser_image(uid,image);
    }

    /**
     * 支付请求接口
     */
    static Integer coins;
    static Integer uid;
    static String orderId;
    @GetMapping("/pay") // 订单id（不能重复）和消费金额
    public void pay(@RequestParam("uid") Integer id,@RequestParam("cost") String cost, HttpServletResponse response){
        try {
            coins = Integer.parseInt(cost) * 10;
            uid = id;
            System.out.println(coins+uid+"add");
            Thread.sleep(10);
            orderId = String.valueOf(Instant.now().toEpochMilli());
            AlipayClient alipayClient = AlipayConfig.getAlipayClient();
            // 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            AlipayTradePayModel model = new AlipayTradePayModel();
            // 设定订单号 必须要写,且订单号不能重复，目前已经只是做测试，已经写死
            model.setOutTradeNo(orderId);
            // 设置订单金额
            model.setTotalAmount(cost);
            // 订单名字
            model.setSubject("金币充值");
            // 订单描述
            model.setBody("金币");
            // 产品码
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            // 设置参数
            alipayRequest.setBizModel(model);

            // 设置回调地址
            String url = "http://localhost:9527/index.html";
            alipayRequest.setReturnUrl(url);
            alipayRequest.setNotifyUrl("https://9354fg166ac4.vicp.fun/users/success");
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //    usersMapper.czCoins(coins,uid);
    /**
     * 支付成功后，回调页面
     */
    @PostMapping("success")
    public void success(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        //充值
        usersMapper.czCoins(coins,uid);
        response.getWriter().println("订单Id为"+orderId+"的订单已经成功支付");
    }

    @GetMapping("likes")
    public String Like(@RequestParam("uid") Integer uid, @RequestParam("pid") Integer pid, @RequestParam("likes") Integer likes,
                       @RequestParam("shares") Integer shares, @RequestParam("coins") Integer coins,@RequestParam("otherid") Integer otherid){
        return usersService.Like(uid,pid,likes,shares,coins,otherid);
    }


    @GetMapping("findText")
    public List<Bulletins> findText(@RequestParam("uid") Integer uid){
        return usersService.findText(uid);
    }

    @GetMapping("addText")
    public void addText(@RequestParam("uid") Integer uid,@RequestParam("content") String content){
        usersService.addText(uid,content);
    }

    @GetMapping("userDetails")
    public Users userDetails(@RequestParam("uid") Integer uid){
        return usersService.userDetails(uid);
    }

    @GetMapping("addApply")
    public void addApply(@RequestParam("uid") Integer uid,@RequestParam("bid") Integer bid){
        usersService.addApply(uid,bid);
    }

    @GetMapping("/qqlogin")
    public void QQlogin(@RequestParam("qq") String qq, HttpServletResponse response) throws IOException {
        // 模拟登录成功与否
        boolean loggedIn = qq.equals("123456789"); // 替换成实际的登录逻辑

        if (loggedIn) {
            response.sendRedirect("https://9354fg166ac4.vicp.fun/tb_index.html");
        } else {
            // 登录不成功时的处理，例如重定向到错误页面
            response.sendRedirect("/error");
        }
    }

    @GetMapping("updateCoins")
    public void updateCoins(@RequestParam("uid") Integer uid,@RequestParam("coins") Integer coins){
        usersMapper.updateCoins(uid,coins);
    }
    @Resource
    private RedisTemplate<String, List<String>> redisTemplate;

    @GetMapping("getDate")
    public List<String> getDate(@RequestParam("uid") Integer uid) {
        // 首先尝试从 Redis 缓存中获取数据
        String cacheKey = "listDate:" + uid;
        List<String> cachedUser = redisTemplate.opsForValue().get(cacheKey);

        if (cachedUser != null) {
            // 如果缓存中有数据，直接返回缓存数据
            return cachedUser;
        }

        // 如果缓存中没有数据，则从数据库中获取数据（这里的逻辑需要根据实际情况进行调整）
        List<String> userFromDB = new ArrayList<>();

        if (userFromDB != null) {
            // 将从数据库中获取的数据存入 Redis 缓存
            // 设置缓存时间为40天
            redisTemplate.opsForValue().set(cacheKey, userFromDB, 40, TimeUnit.DAYS);
            return userFromDB;
        } else {
            // 数据库中没有找到对应用户，返回空对象或者其他处理
            return new ArrayList<>(); // 返回空对象示例
        }
    }

    @GetMapping("makeDate")
    public String makeDate(@RequestParam("uid") Integer uid, @RequestParam("date") String date) {
        String cacheKey = "listDate:" + uid;

        // 尝试从 Redis 缓存中获取数据
        List<String> cachedUser = redisTemplate.opsForValue().get(cacheKey);

        // 如果缓存中不存在用户的日期列表，则初始化一个新的列表
        if (cachedUser == null) {
            cachedUser = new ArrayList<>();
        }

        // 向用户的最后登录日期列表添加新的日期
        cachedUser.add(date);
        // 设置缓存时间为40天
        redisTemplate.opsForValue().set(cacheKey, cachedUser, 40, TimeUnit.DAYS);
        // 更新 Redis 缓存中的数据
        redisTemplate.opsForValue().set(cacheKey, cachedUser);

        return "ok";
    }

    @GetMapping("addEx")
    public void addEx(@RequestParam("uid") Integer uid){
        usersMapper.addEx(uid);
    }



}















